<template>
	<view class="container" :style="[{paddingTop:CustomBar+'px'}]">
		<!-- #ifdef APP-PLUS -->
		<view class="app-login">
			<image src="https://xarkbucket.oss-cn-hangzhou.aliyuncs.com/%E5%85%8D%E5%8D%95%E9%80%9AApp/login-bg.png" class="bg"
			 mode=""></image>
			<trans-custom bgColor="243,73,48" :isBack="true" :opacity="'0'">
				<block slot="backText"></block>
			</trans-custom>
			<view :style="[{height:winHeight+'px'}]" class="login-content">
				<transition enter-active-class="animated slideInRight animationConfig" leave-active-class="animated slideOutRight animationConfig">
					<view class="note" v-if="is_phone_login">
						<view class="top-title">
							<text>您好，</text>
							<text>欢迎来到免单时代聚合算</text>
						</view>
						<view class="phone-input">
							<view class="">+86</view>
							<input type="number" v-model="phone" maxlength="11" placeholder-style="color: #999;" placeholder="请输入手机号码" />
						</view>
						<view class="tips">
							未注册的手机号验证后自动创建掌商账户
						</view>
						<view class="get-code" @click='switchKeyboard(6)'>
							获取短信验证码
						</view>
					</view>
				</transition>
				<transition enter-active-class="animated slideInRight animationConfig" leave-active-class="animated slideOutRight animationConfig">
					<view v-if="is_acc_pass_login" class="note">
						<view class="top-title">
							<text>您好，</text>
							<text>欢迎来到免单时代聚合算</text>
						</view>
						<view class="phone-input tui-line-cell">
							<tui-icon name="mobile" size="20" color='#999999'></tui-icon>
							<input class="tui-input" v-model="account" placeholder-class="phcolor" placeholder="请输入账号/手机号" />
						</view>
						<view class="phone-input tui-line-cell">
							<tui-icon name="pwd" size="20" color='#999999'></tui-icon>
							<input class="tui-input" v-model="password" type="password" placeholder-class="phcolor" placeholder="请输入密码" />
						</view>
						<view class="get-code" @click='passLogin' style="margin-top:60rpx">
							立即登录
						</view>
					</view>
				</transition>
			</view>
			<view class="bottom-text">
				<view class="change-login">
					<view :class="is_acc_pass_login?'active':''" @click="passwordLoginTr">账号密码登录</view>
					<view class=""></view>
					<view :class="is_phone_login?'active':''" @click="phoneLoginTr">快捷方式登录</view>
				</view>

				<view class="login-tips">
					登录即代表您已同意掌商用户协议、隐私政策、并授权使用您的掌商账号信息(如昵称、头像、收货地址等)以便您进行统一管理
				</view>
				<tui-footer :fixed="false" :copyright="copyright"></tui-footer>
			</view>
			<tui-keyboard :show="show" @close="closeKeyboard" @click="keyboardClick">
				<view class="tui-digital-box">
					<view class="tui-keyboard-tips">请输入短信验证码</view>
					<tui-keyboard-input :inputvalue.sync="pwdArr"></tui-keyboard-input>
				</view>
			</tui-keyboard>
		</view>
		<!-- #endif -->


		<!-- #ifdef MP-WEIXIN -->
		<view class="weixin-login" :style="[{height:winHeight+'px'}]">
			<cu-custom bgColor="bg-white" :isBack="true" fatherCss="box-shadow:none">
				<block slot="backText"></block>
				<block slot="content">微信授权登录</block>
			</cu-custom>
			<view class="logo-name">
				<!-- 掌商 logo -->
				<image src="https://xarkbucket.oss-cn-hangzhou.aliyuncs.com/%E5%85%8D%E5%8D%95%E9%80%9AApp/logo-login-befree-zs.png"
				 mode=""></image>
				<view class="">
					掌商
				</view>
			</view>
			<view class="tips">
				请完成微信授权以继续使用
			</view>
			<button class="get_userinfo" open-type="getUserInfo" @getuserinfo="getUserInfo">微信授权用户信息</button>
			<view   class="get_userinfo no-login" @click="nextUrl">
				暂不登录
			</view>
			<view class="p-bot">
				授权代表您已同意<text @click="goAgree">掌商平台用户协议，隐私协议</text>
			</view>
		</view>
		<!-- #endif -->
		<!-- #ifdef H5 -->
		<view class="weixin-login" :style="[{height:winHeight+'px'}]">
			<cu-custom bgColor="bg-white" :isBack="true" fatherCss="box-shadow:none">
				<block slot="backText"></block>
				<block slot="content">授权登录</block>
			</cu-custom>
			<view class="logo-name">
				<image src="https://xarkbucket.oss-cn-hangzhou.aliyuncs.com/%E5%85%8D%E5%8D%95%E9%80%9AApp/logo-login-befree-zs.png"
				 mode=""></image>
				<view class="">
					掌商
				</view>
			</view>
			<view class="tips">
				请完成微信授权以继续使用
			</view>
			<view class="get_userinfo" @click="gzhLogin">授权登录</view>
		</view>
		<!-- #endif -->
	</view>
</template>

<script>
	import wechatAuth from '@/static/js/wechatAuth.js' // 微信登录插件
	const qs = require('qs')
	import Vue from 'vue'
	import tuiFooter from "./component/footer"
	import tuiKeyboard from "@/components/thorUI/keyboard"
	import tuiKeyboardInput from "@/components/thorUI/keyboard-input"
	import tuiIcon from "@/components/thorUI/icon"
	export default {
		components: {
			tuiFooter,
			tuiKeyboard,
			tuiKeyboardInput,
			tuiIcon
		},
		data() {
			return {
				CustomBar: this.CustomBar,
				winHeight: 0,
				copyright: "Copyright © 2019-06 掌商",
				phone: '',
				show: false,
				numberArr: [],
				pwdArr: ["", "", "", "", "", ""],
				temp: ["", "", "", "", "", ""],
				localCode: '',
				back_url: '',
				// 是否是账号密码登录
				is_acc_pass_login: false,
				is_phone_login: true,

				// 账号密码登录
				account: '',
				password: '',

				// 微信登录码
				loginCode: ''
			}
		},
		onLoad(options) {
			var that = this
			let next = options.next
			this.back_url = next
			setTimeout(() => {
				uni.getSystemInfo({
					success: function(res) {
						that.winHeight = res.windowHeight - that.CustomBar
					}
				})
			}, 50)
			// #ifdef H5
			if (uni.getStorageSync('gzhLoginBackUrl')) {
				this.back_url = uni.getStorageSync('gzhLoginBackUrl').split('=')[1]
				uni.removeStorageSync('gzhLoginBackUrl')
			}
			Vue.use(wechatAuth, {
				appid: 'wx7ce0d29b811eb3f3'
			})
			let url = window.location.href
			if (url.indexOf('code') > -1 && url.indexOf('state') > -1) {
				wechatAuth.returnFromWechat(url)
				this.gzhCodeLogin(wechatAuth.code)
			}
			// #endif


		},
		onReady() {
			uni.setNavigationBarColor({
				frontColor: '#000000',
				backgroundColor: '#ffffff'
			})
		},
		methods: {
			// 微信小程序登录
			getUserInfo(res) {
				var that = this
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						that.$request({
							url: '/user/login',
							method: 'post',
							data: {
								code: loginRes.code,
								encryptedData: encodeURIComponent(res.detail.encryptedData),
								iv: encodeURIComponent(res.detail.iv),
							},
							success: res => {
								if (res.data.status == 1) {
									that.loginCode = loginRes.code
									uni.setStorageSync('userInfo', res.data.data.user_info)
									uni.setStorageSync('wxSessionKey', res.data.data.wx_session_key)
									if(that.back_url.indexOf('offlinePay')>-1){
										that.nextUrl()
									}else{
										uni.redirectTo({
											url: '/pages/phoneGetSet?loginCode=' + encodeURIComponent(res.data.data.wx_session_key) + '&next=' +
												that.back_url,
											success: res => {},
											fail: () => {},
											complete: () => {}
										});
									}
								}
							},
							fail: () => {},
							complete: () => {}
						});

					}
				});

			},
			// 公众号code登录
			gzhCodeLogin(code) {
				var that = this
				that.$request({
					url: '/user/login',
					method: 'post',
					data: {
						code: code,
					},
					success: res => {
						if (res.data.status == 1) {
							uni.showLoading({
								title: '登录成功，跳转中',
								mask: true
							});
							wx.setStorageSync('userInfo', res.data.data.user_info)
							setTimeout(function() {
								that.nextUrl()
							}.bind(that), 1000)
						}
					},
					fail: () => {},
					complete: () => {}
				});
			},
			// app登录
			// 快捷登录
			phoneLoginTr() {
				this.is_phone_login = true
				this.is_acc_pass_login = false
			},
			// 账号密码登录
			passwordLoginTr() {
				this.is_acc_pass_login = true
				this.is_phone_login = false
			},
			switchKeyboard(index) {
				var that = this
				let length = index; //e.currentTarget.dataset.length;
				if (this.phone == '') {
					uni.showToast({
						title: '请先输入手机号码',
						icon: 'none'
					})
					return
				}
				let arr = ["", "", "", "", "", ""]
				if (length == 4) {
					arr = ["", "", "", ""]
				}

				this.$request({
					url: '/login/sendSmsCode',
					data: {
						phone: that.phone
					},
					success: res => {
						if (res.data.status == 1) {
							// 正确密码
							uni.showToast({
								title: '短信发送成功'
							})
							that.localCode = res.data.data
							that.pwdArr = arr;
							that.temp = arr;
							that.numberArr = [];
							that.show = true
						}
						// uni.hideLoading()
					},
					fail: () => {},
					complete: () => {}
				});
			},
			closeKeyboard: function() {
				this.show = false;
				this.numberArr = [];
				this.pwdArr = this.temp
			},
			getPwd: function() {
				var that = this
				//判断并取出密码
				if (this.numberArr.length === this.pwdArr.length) {
					var pwd = this.numberArr.join('')
					if (pwd != that.localCode) {
						uni.showToast({
							title: '验证码有误',
							complete() {
								that.numberArr = [];
								that.pwdArr = ["", "", "", "", "", ""]
							}
						})
						return false
					}
					this.$request({
						url: '/login/login',
						data: {
							login_type: 1,
							phone: that.phone
						},
						success: res => {
							if (res.data.status == 1) {
								uni.showLoading({
									title: '登录成功，跳转中',
									mask: true
								});
								that.nextUrl()
								return
							}
							// uni.hideLoading()
						},
						fail: () => {},
						complete: () => {}
					});
				}
			},
			passLogin() {
				var that = this;
				var account = that.account;
				var password = that.password;
				if (account == '') {
					uni.showToast({
						title: '请输入账号/手机号',
						icon: 'none'
					})
					return false
				}
				if (password == '') {
					uni.showToast({
						title: '请输入密码',
						icon: 'none'
					})
					return false
				} else if (password.length < 6 || password.length > 18) {
					uni.showToast({
						title: '密码为6~12为数字、字母组成',
						icon: 'none'
					})
					return false
				}
				this.$request({
					url: '/login/login',
					data: {
						login_type: 2,
						password: that.password,
						phone: that.account
					},
					success: res => {
						if (res.data.status == 1) {
							uni.showLoading({
								title: '登录成功，跳转中',
								mask: true
							});
							that.nextUrl()
							return
						}
						// uni.hideLoading()
					},
					fail: () => {},
					complete: () => {}
				});

			},
			nextUrl() {
				// 跳转页面
				var next_url = decodeURIComponent(this.back_url)
				next_url = next_url.replace(/%2F/g, '/')
				next_url = next_url.replace(/%3F/g, '?')
				next_url = next_url.replace(/%3D/g, '=')
				next_url = next_url.replace(/%26/g, '&')
				uni.getStorageSync('needOnload', true)
				uni.redirectTo({
					url: next_url,
					fail: function() {
						uni.switchTab({
							url: next_url
						});
					}
				})
			},
			goAgree(){
				uni.navigateTo({
					url: '/pages/userAgree?type=yonghu'
				})
			},
			keyboardClick: function(e) {
				let numberArr = this.numberArr;
				let pwdArr = this.pwdArr;
				let index = e.index;
				if (numberArr.length === pwdArr.length || index == undefined) {
					return;
				}
				if (index == 9) { //取消键
					this.closeKeyboard();
					return;
				} else if (index == 11) {
					//退格键
					let len = numberArr.length;
					if (len) {
						pwdArr.splice(len - 1, 1, "");
					} else {
						pwdArr = this.temp;
					}
					numberArr.pop()
				} else if (index == 10) {
					numberArr.push(0);
					pwdArr.splice(numberArr.length - 1, 1, "●");
				} else {
					numberArr.push(index + 1);
					pwdArr.splice(numberArr.length - 1, 1, "●");
				}
				this.numberArr = numberArr;
				this.pwdArr = pwdArr;
				this.getPwd();
			},

			// 公众号授权
			gzhLogin() {
				// 微信未授权登录跳转到授权登录页面
				let url = window.location.href
				// 解决重复登录url添加重复的code与state问题
				let parseUrl = qs.parse(url.split('?')[1])
				let loginUrl
				if (parseUrl.code && parseUrl.state) {
					delete parseUrl.code
					delete parseUrl.state
					loginUrl = `${url.split('?')[0]}?${qs.stringify(parseUrl)}`
				} else {
					loginUrl = url
				}
				uni.setStorageSync('gzhLoginBackUrl', loginUrl.split('?')[1])
				wechatAuth.redirectUri = loginUrl.split('?')[0]
				window.location.href = wechatAuth.authUrl

			}
		}
	}
</script>

<style scoped>
	.container {
		box-sizing: border-box;
		width: 100%;
		position: relative;
	}

	.container .bg {
		z-index: 0;
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
		left: 0;
	}

	.login-content {
		width: 100%;
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		position: relative;
	}

	.note {
		z-index: 2;
		position: absolute;
		top: 130rpx;
		left: 50%;
		width: 640rpx;
		height: 630rpx;
		margin-left: -320rpx;
		background-color: #ffffff;
		border-radius: 16rpx;
		padding: 60rpx 40rpx 0;
		box-sizing: border-box;
		box-shadow: 10rpx 10rpx 8rpx 0 rgba(217, 54, 30, .5);
	}

	.top-title {
		width: 100%;
		height: 140rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.top-title text {
		font-size: 48rpx;
		color: #333333;
	}

	.phone-input {
		width: 100%;
		padding: 20rpx 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: solid 1rpx #efefef;
		margin-top: 20rpx
	}

	.phone-input>view {
		width: 75rpx;
		color: #666;
		font-size: 30rpx;
		/* text-align: center; */
		/* font-weight: bold; */
	}

	.phone-input>input {
		flex: 1;
		height: 50rpx;
		line-height: 50rpx;
		color: #333;
		font-size: 30rpx;
		margin-left: 20rpx;
	}

	.tips {
		font-size: 24rpx;
		color: #999;
		margin-top: 30rpx;
	}

	.get-code {
		width: 100%;
		height: 88rpx;
		text-align: center;
		line-height: 88rpx;
		border-radius: 4rpx;
		margin-top: 85rpx;
		font-size: 32rpx;
		background-image: linear-gradient(0deg,
			#f34930 0%,
			#fe7b68 100%),
			linear-gradient(#f34930,
			#f34930);
		border-radius: 48rpx;
		color: #fff
	}

	.bottom-text {
		width: 700rpx;
		position: absolute;
		bottom: 20rpx;
		left: 50%;
		margin-left: -350rpx;
		display: flex;
		flex-direction: column;
	}

	.bottom-text .change-login {
		width: 100%;
		height: 60rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.bottom-text .change-login .active {
		font-size: 30rpx;
	}

	.bottom-text .change-login>view {
		color: #fff;
		font-size: 26rpx;
	}

	.bottom-text .change-login>view:nth-child(2) {
		height: 20rpx;
		width: 2rpx;
		background: #f5f5f5;
		margin: 0 20rpx
	}

	.bottom-text .login-tips {
		font-size: 22rpx;
		color: #fff;
	}

	.bottom-text .login-tips text {
		color: #f34930;
	}

	.header {
		padding: 80upx 90upx 60upx 90upx;
		box-sizing: border-box;
	}

	.title {
		font-size: 34upx;
		color: #333;
		font-weight: 500;
	}

	.sub-title {
		font-size: 24upx;
		color: #7a7a7a;
		padding-top: 18upx;
	}

	.tui-btn-box {
		padding: 10upx 40upx;
		box-sizing: border-box;
	}

	.tui-btn-class {
		margin-top: 36upx;
	}

	.tui-keyboard-tips {
		width: 100%;
		height: 120upx;
		line-height: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30upx;
		background: #fff;
		position: relative;
		color: #333;
		border: 0;
	}

	.tui-digital-box {
		background: #fff;
		padding-bottom: 50upx;
		border: 0;
	}

	.weixin-login {
		width: 100%;
		background: #fff;
		position: relative;
	}
	
	.p-bot{
		width: 100%;
		height: 100rpx;
		position: absolute;
		bottom: 0;
		left: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 26rpx;
		color: #999;
	}
	
	.p-bot text{
		color: #F34930;
	}

	.weixin-login .logo-name {
		width: 200rpx;
		height: 250rpx;
		display: flex;
		flex-direction: column;
		margin: 100rpx auto 100rpx
	}

	.weixin-login .logo-name image {
		width: 200rpx;
		height: 200rpx;
		border-radius: 100%;
	}

	.weixin-login .logo-name view {
		color: #333;
		text-align: center;
		font-size: 30rpx;
		font-weight: bold;
		line-height: 50rpx;
	}

	.weixin-login .tips {
		line-height: 70rpx;
		font-size: 26rpx;
		color: #616C78;
		text-align: center;
	}

	.get_userinfo {
		background-color: #1AAC1B;
		border-radius: 10rpx;
		margin: 0 auto;
		width: 600rpx;
		text-align: center;
		height: 80rpx;
		line-height: 80rpx;
		color: #fff;
		margin-top: 10rpx;
		border: 1px solid transparent;
		outline: none;
		font-size: 30rpx
	}
	
	.no-login{
		background: #fff !important;
		color: #999 !important;
		border: solid 1rpx #efefef !important;
		margin-top: 20rpx !important;
	}
</style>

<style>
	.tui-footer {
		padding: 10rpx 0 !important;
	}

	.tui-footer-copyright {
		color: #fff !important;
	}
</style>
